package com.practice.reflect;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


class ReflectTarget {
    private String field;

    public ReflectTarget(){
        field = "hello";
    }

    public ReflectTarget(String f){
        field = f;
    }

    public void publicMethod(){
        System.out.println(field);
    }

    private void privateMethod(){
        System.out.println(field);
    }
}

/**
 * Class
 * Method
 * Field
 */
public class Reflect {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得目标Class对象
        Class<?> targetClass = Class.forName("com.practice.reflect.ReflectTarget");

        //创建目标对象实例
        ReflectTarget reflectTarget = (ReflectTarget) targetClass.newInstance();

        //获取对象的方法
        Method[] methods = targetClass.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
        }

        //获取指定方法并调用
        Method method = targetClass.getDeclaredMethod("publicMethod");
        method.invoke(reflectTarget);

        //获得指定属性
        Field field = targetClass.getDeclaredField("field");
        //修改属性
        field.setAccessible(true);
        field.set(reflectTarget,"good");

        //获取私有方法
        Method privateMethod = targetClass.getDeclaredMethod("privateMethod");
        privateMethod.setAccessible(true);
        privateMethod.invoke(reflectTarget);
    }

}
